package me.numark.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import butterknife.Bind;
import me.numark.R;
import me.numark.model.BaseModel;
import me.numark.model.User;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Utils;

/**
 * Created by ytian on 15/7/27.
 */
public class ChooseInterestsActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.right_text)
    TextView rightText;

    @Bind(R.id.ignore_button)
    Button ignoreButton;

    @Bind(R.id.list)
    LinearLayout mList;

    private User mUser;
    int itemHeight;
    int onedp;
    private String weiboId, weiboToken;
    boolean isFromLogin = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_choose_interests;
        super.onCreate(savedInstanceState);
        initUI();
        initParams(getIntent());
        mUser = Global.getGson().fromJson(getIntent().getStringExtra("user"), User.class);
        isFromLogin = getIntent().getBooleanExtra(LogInActivity.EXTRA_FROM_LOGIN,false);
//        getInterests();
        buildList(Global.tags);
    }

    private void initParams(Intent intent) {
        weiboId = intent.getStringExtra("weibo_id");
        weiboToken = intent.getStringExtra("weibo_token");
    }

    private void initUI() {
        backInToolbar.setVisibility(View.INVISIBLE);
        titleTextView.setText(R.string.possibly_interested_tags);
        rightText.setVisibility(View.VISIBLE);
        rightText.setText(R.string.umeng_common_action_continue);
        rightText.setOnClickListener(this);
        ignoreButton.setOnClickListener(this);
    }

    void buildList(BaseModel[] items) {
        mList.removeAllViews();
        int rows = items.length / 2;
        Context context = this;
        itemHeight = Utils.dp2px(context, 35);
        onedp = Utils.dp2px(context, 1);
        for (int i = 0; i < rows; i++) {
            LinearLayout ll = new LinearLayout(context);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            CheckBox cb1 = createCheckBox(context, items[i * 2].title, ll, i * 2);
            CheckBox cb2 = createCheckBox(context, items[i * 2 + 1].title, ll, i * 2 + 1);
            if (i == 0) {
                cb1.setBackgroundResource(R.drawable.interest_item_bg_top_left);
                cb2.setBackgroundResource(R.drawable.interest_item_bg_top_right);
            } else if (i == rows - 1) {
                cb1.setBackgroundResource(R.drawable.interest_item_bg_bottom_left);
                cb2.setBackgroundResource(R.drawable.interest_item_bg_bottom_right);
            } else {
                cb1.setBackgroundResource(R.drawable.interest_item_bg);
                cb2.setBackgroundResource(R.drawable.interest_item_bg);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mList.addView(ll, lp);
        }
    }

    CheckBox createCheckBox(Context context, String text, LinearLayout ll, int pos) {
        final CheckBox cb = new CheckBox(context);
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    favouriteSet.add(cb.getText());
                }else {
                    if (favouriteSet.contains(cb.getText()))
                        favouriteSet.remove(cb.getText());
                }
            }
        });
        cb.setButtonDrawable(null);
        cb.setTextColor(context.getResources().getColorStateList(R.color.interest_item_color));
        cb.setGravity(Gravity.CENTER);
        cb.setText(text);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, itemHeight, 1);
        lp.setMargins(pos % 2 == 1 ? -onedp : 0, pos > 1 ? -onedp : 0, 0, 0);
        ll.addView(cb, lp);
        return cb;
    }

    private HashSet<CharSequence> favouriteSet = new HashSet();

    @Override
    public void onClick(View v) {
      final Intent intent = new Intent(this, AddFriendsActivity.class);
        intent.putExtra(LogInActivity.EXTRA_FROM_LOGIN,isFromLogin);
        intent.putExtra("user_id", mUser.uid);
        if (!TextUtils.isEmpty(weiboId)) {
            intent.putExtra("weibo_id", weiboId);
        }
        if (!TextUtils.isEmpty(weiboToken)) {
            intent.putExtra("weibo_token", weiboToken);
        }
        switch (v.getId()) {
            case R.id.right_text:
                new RequestServerTask<BaseResponse>(BaseResponse.class) {
                    @Override
                    protected String requestServer() {
                        Map<String, Object> params = new HashMap<>();

                        params.put("favourite", TextUtils.join("|", favouriteSet));
                        return HttpUtil.post(String.format(NetworkConstants.REGISTER_FAVORITE_URL,mUser.uid), params);

                    }


                    @Override
                    protected void onSuccess(BaseResponse result) {
                        Utils.showToast(R.string.add_interest_success);
                        startActivityForResult(intent, 0);
                    }
                }.start();

                break;
            case R.id.ignore_button:
                startActivityForResult(intent, 0);
                break;
        }
    }
/*
    private void getInterests() {
        final Map<String, String> header = new HashMap<>();
        header.put("uid", String.valueOf(mUser.uid));
        header.put("token", String.valueOf(mUser.token));
        final String url = String.format(NetworkConstants.REGISTER_FAVORITE_URL, String.valueOf(mUser.uid));
        new RequestServerTask<BaseListResponse>(BaseListResponse.class, this, getString(R.string.getting_topics)) {
            @Override
            protected String requestServer() {
                return HttpUtil.get(url, null, header);
            }

            @Override
            protected void onSuccess(BaseListResponse result) {
                if (result.data != null) {
                    buildList(result.data);
                }
            }
        }.start();
    }
*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        setResult(RESULT_OK);
        finish();
    }
}
